<?php

namespace app\modules\v1\components;

use common\libraries\ResourceLoader;
use common\libraries\WriteLogSrv;
use common\models\db\User;
use Yii;

/**
 * 基础控制器
 */
class BaseController extends \common\components\BaseController
{
    use \app\traits\controller\Validate;

    public $userId = 0;
    public $sessionId = '';
    public $user = null;
    protected $setting = [];
    public $request;
    
    // 不需要登录验证的接口
    protected $noAuthActions = [
        'user/login',
        'loan/rate-options',
        'api/get-access-token'
    ];

    /**
     * 控制器初始化
     */
    public function init()
    {
        $this->request = Yii::$app->request;
        $input = file_get_contents("php://input");

        WriteLogSrv::writeLog(Yii::$app->getRequest()->url . '：' . $input);
        // $this->setting = Setting::findValidOne()->getAttributes();
        
        // 验证用户登录状态
        $this->checkLogin();
    }
    
    /**
     * 在执行action之前验证是否需要登录
     * @param \yii\base\Action $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        if (!parent::beforeAction($action)) {
            return false;
        }
        
        // 获取当前请求的路由
        $route = $action->controller->id . '/' . $action->id;
        
        // 检查是否需要登录验证
        if (!in_array($route, $this->noAuthActions)) {
            // 如果用户未登录，返回错误
            if (!$this->user) {
                $this->error('用户未登录或登录已过期', 401);
                return false;
            }
        }
        
        return true;
    }

    /**
     * @param string $aArg
     * @param string $default
     * @return mixed|string
     */
    protected function getPostData($aArg = '', $default = '')
    {
        $input = file_get_contents("php://input");
        $data = json_decode($input, true);
        if (!empty($aArg)) {
            $data = isset($data[$aArg]) ? $data[$aArg] : $default;
        }
        return $data;
    }

    /**
     * 获取图片地址
     */
    public function getPicUrl($list, $key = '')
    {
        if (is_array($list)) {
            foreach ($list as $k => $v) {
                $v[$key] = !empty($v[$key]) ? ResourceLoader::formatUrl($v[$key]) : '';
                $list[$k] = $v;
            }
        } else {
            $list = !empty($list) ? ResourceLoader::formatUrl($list) : '';
        }

        return $list;
    }

    /**
     * 处理jsonData
     */
    public function getJsonData($data, $key = '')
    {
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                $data[$k][$key] = json_decode($v[$key], true);
            }
        } else {
            $data = json_decode($data, true);
        }
        return $data;
    }

    /**
     * @param \yii\base\Action $action
     * @param mixed $result
     * @return mixed
     */
    public function afterAction($action, $result)
    {
        $key = Yii::$app->getRequest()->url . $this->sessionId;
        WriteLogSrv::writeLog('删除：' . $key);
        Access::delCacheValue($key);
        return parent::afterAction($action, $result);
    }
    
    /**
     * 验证用户登录状态
     * @return bool
     */
    protected function checkLogin()
    {
        // 获取请求头中的Authorization
        $authHeader = Yii::$app->request->headers->get('Authorization');
        
        if ($authHeader && preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
            $token = $matches[1];
            
            // 解析token
            $tokenData = $this->parseToken($token);
            
            if ($tokenData) {
                $userId = $tokenData['userId'];
                
                // 查询用户
                $user = User::findOne($userId);
                
                if ($user) {
                    $this->userId = $userId;
                    $this->user = $user;
                    return true;
                }
            }
        }
        
        return false;
    }
    
    /**
     * 解析token
     * @param string $token
     * @return array|null
     */
    protected function parseToken($token)
    {
        // 分离token数据和签名
        $parts = explode('.', $token);
        
        if (count($parts) != 2) {
            return null;
        }
        
        $tokenData = base64_decode($parts[0]);
        $signature = $parts[1];
        
        if (!$tokenData) {
            return null;
        }
        
        $tokenData = json_decode($tokenData, true);
        
        if (!isset($tokenData['userId']) || !isset($tokenData['openId']) || !isset($tokenData['timestamp'])) {
            return null;
        }
        
        // 验证签名
        $expectedSignature = md5($tokenData['userId'] . $tokenData['openId'] . $tokenData['timestamp'] . Yii::$app->params['tokenSecret']);
        
        if ($signature !== $expectedSignature) {
            return null;
        }
        
        // 验证token是否过期
        $tokenExpire = Yii::$app->params['tokenExpire'] ?? (7 * 24 * 3600); // 默认7天
        
        if (time() - $tokenData['timestamp'] > $tokenExpire) {
            return null;
        }
        
        return $tokenData;
    }
}
